<template>
  <div class="explosion-container">
    <!-- 标题栏 -->
    <div class="page-header">
      <h1>发电机三维爆炸图</h1>
      <p>通过三维结构爆炸图展示发电机各部件的结构和位置关系</p>
    </div>

    <!-- 三维视图容器 -->
    <div class="godot-container">
      <iframe
        ref="godotFrame"
        :src="godotSrc"
        class="godot-iframe"
        frameborder="0"
        @load="handleGodotLoaded"
      ></iframe>
    </div>

    <!-- 部件信息弹窗 -->
    <div
      v-if="showPartDialog"
      class="dialog-overlay"
      @click.self="closePartDialog"
    >
      <div class="dialog-content">
        <div class="dialog-header">
          <h2>{{ currentPart?.title || "部件信息" }}</h2>
          <button class="close-button" @click="closePartDialog">×</button>
        </div>
        <div class="dialog-body">
          <div v-if="currentPart" class="part-detail">
            <img
              v-if="currentPart.image"
              :src="currentPart.image"
              :alt="currentPart.title"
              class="part-image"
            />
            <div class="part-info">
              <h3>{{ currentPart.title }}</h3>
              <p class="part-content">{{ currentPart.content }}</p>
              <div v-if="currentPart.details" class="part-details">
                <h4>详细信息</h4>
                <ul>
                  <li
                    v-for="(detail, index) in currentPart.details"
                    :key="index"
                  >
                    {{ detail }}
                  </li>
                </ul>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, onUnmounted, nextTick } from "vue";
import { ElMessage } from "element-plus";

// 状态管理
const godotFrame = ref(null);
const showPartDialog = ref(false);
const currentPart = ref(null);
const godotSrc = ref("/godot/task_copy.html"); // Godot页面路径

// 发电机部件信息配置
const generatorParts = {
  stator: {
    id: "stator",
    title: "发电机定子",
    content: "发电机定子是发电机的核心部件之一，由铁芯、绕组和机座组成。",
    image: "/src/assets/generator_body.png", // 替换为实际图片路径
    details: [
      "定子铁芯由硅钢片叠压而成，用于减小涡流损耗",
      "定子绕组采用多相绕组结构，用于产生感应电动势",
      "机座提供机械支撑和保护作用",
    ],
  },
  rotor: {
    id: "rotor",
    title: "发电机转子",
    content: "转子是发电机的旋转部分，用于产生旋转磁场。",
    image: "/src/assets/generator_body.png", // 替换为实际图片路径
    details: [
      "转子绕组通以直流电，产生磁场",
      "由转轴、磁轭和绕组等组成",
      "高速旋转时需要考虑动平衡问题",
    ],
  },
  exciter: {
    id: "exciter",
    title: "励磁机",
    content: "励磁机提供发电机转子所需的直流励磁电流。",
    image: "/src/assets/exciter.png",
    details: [
      "通常为小型发电机结构",
      "提供稳定的励磁电流",
      "与主发电机同轴连接",
    ],
  },
  "pilot-exciter": {
    id: "pilot-exciter",
    title: "副励磁机",
    content: "副励磁机为自动电压调节器提供电源。",
    image: "/src/assets/exciter.png", // 替换为实际图片路径
    details: [
      "通常采用永磁发电机",
      "不受主发电机运行状态影响",
      "提供稳定的初始励磁电源",
    ],
  },
  bearing: {
    id: "bearing",
    title: "轴承",
    content: "轴承支撑发电机转子，减少转动摩擦。",
    image: "",
    details: [
      "主要采用滑动轴承或滚动轴承",
      "需要定期润滑维护",
      "监测轴承温度是重要的运行参数",
    ],
  },
  "cooling-system": {
    id: "cooling-system",
    title: "冷却系统",
    content: "冷却系统用于散热，保证发电机正常运行温度。",
    image: "",
    details: [
      "常见冷却方式有空气冷却、水冷却等",
      "冷却效果直接影响发电机容量",
      "需要定期清理维护以保证散热效果",
    ],
  },
  "end-cover": {
    id: "end-cover",
    title: "端盖",
    content: "端盖保护发电机内部部件，提供轴承支撑。",
    image: "",
    details: [
      "通常采用铸铁或铸钢材料",
      "与机座配合形成封闭空间",
      "为轴承提供安装位置",
    ],
  },
};

// 处理Godot页面加载完成
const handleGodotLoaded = () => {
  ElMessage.success("三维模型加载完成");
  // 可以在这里向Godot页面发送初始消息
  sendMessageToGodot({ type: "init", data: {} });
};

// 向Godot页面发送消息
const sendMessageToGodot = (message) => {
  if (godotFrame.value && godotFrame.value.contentWindow) {
    try {
      godotFrame.value.contentWindow.postMessage(message, "*");
    } catch (error) {
      console.error("发送消息到Godot失败:", error);
    }
  }
};

// 处理部件点击，显示详细信息弹窗
const showPartDetails = (partId) => {
  const part = generatorParts[partId];
  if (part) {
    currentPart.value = part;
    showPartDialog.value = true;
  } else {
    ElMessage.warning("未找到该部件的详细信息");
  }
};

// 关闭部件信息弹窗
const closePartDialog = () => {
  showPartDialog.value = false;
  currentPart.value = null;
};

// 处理从Godot页面接收的消息
const handleMessageFromGodot = (event) => {
  try {
    const data = event.data;
    console.log("收到Godot消息:", data);

    // 处理部件点击事件
    if (data.type === "part_clicked") {
      showPartDetails(data.part_id);
    }

    // 处理其他可能的消息类型
    else if (data.type === "loading_progress") {
      console.log("加载进度:", data.progress);
      // 可以在这里显示加载进度条
    } else if (data.type === "error") {
      ElMessage.error(`Godot错误: ${data.message || "未知错误"}`);
    } else if (data.type === "ready") {
      ElMessage.info("三维模型准备就绪");
    }
  } catch (error) {
    console.error("处理Godot消息失败:", error);
  }
};

// 处理键盘按键事件，用于测试部件弹窗
const handleKeyPress = (event) => {
  // 获取所有部件ID数组
  const partIds = Object.keys(generatorParts);

  // 数字键1-9对应不同部件
  if (event.key >= "1" && event.key <= "9") {
    const index = parseInt(event.key) - 1;
    if (index < partIds.length) {
      const partId = partIds[index];
      showPartDetails(partId);
      ElMessage.info(`已显示 ${generatorParts[partId].title} 的信息`);
    }
  }
  // ESC键关闭弹窗
  else if (event.key === "Escape") {
    closePartDialog();
    ElMessage.info("已关闭弹窗");
  }
  // 显示帮助信息
  else if (event.key === "h" || event.key === "H") {
    ElMessage.info("按数字键1-9查看不同部件信息，按ESC键关闭弹窗");
  }
};

// 生命周期钩子
onMounted(async () => {
  // 等待DOM更新
  await nextTick();

  // 添加消息事件监听器
  window.addEventListener("message", handleMessageFromGodot);

  // 添加键盘事件监听器
  window.addEventListener("keydown", handleKeyPress);

  // 确保iframe已加载
  if (godotFrame.value && godotFrame.value.contentWindow) {
    setTimeout(() => {
      sendMessageToGodot({ type: "init", data: {} });
    }, 1000);
  }

  // 显示键盘操作提示
  setTimeout(() => {
    ElMessage.info("提示：按数字键1-9可测试不同部件弹窗，按H键查看帮助");
  }, 1500);
});

onUnmounted(() => {
  // 移除消息事件监听器
  window.removeEventListener("message", handleMessageFromGodot);
  // 移除键盘事件监听器
  window.removeEventListener("keydown", handleKeyPress);
});
</script>

<style scoped>
.explosion-container {
  display: flex;
  flex-direction: column;
  height: 100vh;
  background-color: #f5f5f5;
}

.page-header {
  background-color: #1976d2;
  color: white;
  padding: 20px;
  text-align: center;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.page-header h1 {
  margin: 0 0 10px 0;
  font-size: 28px;
}

.page-header p {
  margin: 0;
  font-size: 16px;
  opacity: 0.9;
}

.godot-container {
  flex: 1;
  display: flex;
  justify-content: center;
  align-items: center;
  padding: 0;
  position: relative;
}

.godot-iframe {
  width: 100%;
  height: 100%;
  border-radius: 0;
  box-shadow: none;
  background-color: #000;
}

/* 弹窗样式 */
.dialog-overlay {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: rgba(0, 0, 0, 0.5);
  display: flex;
  justify-content: center;
  align-items: center;
  z-index: 1000;
}

.dialog-content {
  background-color: white;
  border-radius: 8px;
  width: 90%;
  max-width: 800px;
  max-height: 80vh;
  overflow: hidden;
  display: flex;
  flex-direction: column;
  box-shadow: 0 8px 32px rgba(0, 0, 0, 0.2);
}

.dialog-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 20px;
  border-bottom: 1px solid #e0e0e0;
  background-color: #f8f9fa;
}

.dialog-header h2 {
  margin: 0;
  color: #1976d2;
  font-size: 24px;
}

.close-button {
  background: none;
  border: none;
  font-size: 28px;
  cursor: pointer;
  color: #666;
  width: 40px;
  height: 40px;
  display: flex;
  justify-content: center;
  align-items: center;
  border-radius: 4px;
  transition: background-color 0.2s;
}

.close-button:hover {
  background-color: #e0e0e0;
  color: #333;
}

.dialog-body {
  padding: 20px;
  overflow-y: auto;
  flex: 1;
}

.part-detail {
  display: flex;
  flex-direction: column;
  gap: 20px;
}

.part-image {
  width: 100%;
  max-width: 300px;
  border-radius: 4px;
  align-self: center;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.part-info h3 {
  color: #1976d2;
  margin-top: 0;
}

.part-content {
  line-height: 1.6;
  color: #333;
}

.part-details h4 {
  color: #666;
  margin-top: 15px;
}

.part-details ul {
  padding-left: 20px;
  margin-bottom: 0;
}

.part-details li {
  margin-bottom: 8px;
  line-height: 1.5;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .godot-container {
    padding: 0;
  }

  .dialog-content {
    width: 95%;
    max-height: 90vh;
  }

  .part-detail {
    flex-direction: column;
  }
}
</style>